#!/usr/bin/bash

configExistenceFlag="false"
[[ -n $(grep -Ps "^kernel\.randomize_va_space\s*=.*" /run/sysctl.d/*.conf /etc/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf /lib/sysctl.d/*.conf /etc/sysctl.conf) ]] && configExistenceFlag="true"

if [[ $configExistenceFlag == "false" ]] ; then
    echo "kernel.randomize_va_space = 2" >> /etc/sysctl.d/50-kernel_sysctl.conf
    sysctl -w kernel.randomize_va_space=2
else
    grep -Ps "^kernel\.randomize_va_space\s*=.*" /run/sysctl.d/*.conf /etc/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf /lib/sysctl.d/*.conf /etc/sysctl.conf | grep -Pvs "kernel.randomize_va_space\s*=\s*2\s*$" | cut -f1 -d: | while read filename; do sed -ri 's/^kernel\.randomize_va_space.*/kernel.randomize_va_space = 2/g' $filename; done;
    sysctl -w kernel.randomize_va_space=2
fi
